// import { isWeChatBrowser } from '@/config/h5/index'
import appBackMainPage from '@/services/h5/app-api/appBackMainPage.js'
import getAgentData from '@/services/h5/app-api/getAgentData.js'
import { ls } from '@/utils/aes'
import { isAndroid, isiOS } from '@/utils/platform'
import { setAuthorization, setCookie } from '@/utils/request'
import NProgress from 'nprogress'

NProgress.configure({ showSpinner: false })
/**
 * 进度条开始
 * @param to
 * @param form
 * @param next
 */
const progressStart = (to, from, next) => {
  // start progress bar
  if (!NProgress.isStarted()) {
    NProgress.start()
  }
  next()
}

/**
 * 获取app返回的值
 * @param to
 * @param form
 * @param next
 * @param options
 */
const setUserInfo = (res, options) => {
  let user = {}
  const accesstoken = res['accessToken']
  const expireAt = new Date(new Date().getTime() + 24 * 60 * 60 * 1000)
  setAuthorization({
    token: accesstoken,
    expireAt: new Date(expireAt)
  })
  user.refreshtoken = res['accessToken']
  ls.set('loginKey', res['publicKey'])
  localStorage.setItem('unloginKey', res['publicKey'])
  const { store } = options
  store.commit('account/setUser', user)
}
const loginGuard = async (to, from, next, options) => {
  let flag = to.meta && to.meta.appAgentToken
  if ((isAndroid || isiOS) && flag) {
    let res = await getAgentData()

    if (isAndroid) {
      res = JSON.parse(res)
    }
    if (
      !res ||
      res.accessToken == 'null' ||
      res.accessToken == '' ||
      res.accessToken == null
    ) {
      appBackMainPage({
        pageIndex: '3'
      })
    } else {
      setUserInfo(res, options)
      next()
    }
  } else {
    document.title = to.name

    next()
  }
}

/**
 * 进度条结束
 * @param to
 * @param form
 * @param options
 */
const progressDone = () => {
  // finish progress bar
  NProgress.done()
}
/**
 * set MenuId to cookie
 * @param {*} to
 * @param {*} from
 * @param {*} options
 */
const mountRouteInfo = (to, from, options) => {
  // reset MenuId
  setCookie('MenuId', '')
  const { store } = options
  const routesConfig = store.getters['account/routesConfig']
  function findRouteExtra(tree, cb) {
    if (tree) {
      for (const child of tree) {
        if (
          child.router &&
          typeof child.router === 'string' &&
          String('/' + child.router).includes(to.path)
        ) {
          cb(child)
          return
        } else if (child.childrenExtra) {
          findRouteExtra(child.childrenExtra, cb)
        } else if (child.children) {
          findRouteExtra(child.children, cb)
        }
      }
    }
  }
  findRouteExtra(routesConfig, child => {
    setCookie('MenuId', child.MenuId)
  })
  // check account.user
  if (!store.state.account.user) {
    store.getters['account/user']
  }
}

export default {
  beforeEach: [progressStart, loginGuard],
  afterEach: [progressDone, mountRouteInfo]
}
